/** 
 * Copyright (C), 2010-2012, AIYOU Software Co.,Ltd. ALL RIGHTS RESERVED. 
 * File name:WebServiceAction.java
 * Version:1.0
 * Date:2012-1-13
 * Description: 
 * author:whh 
 */
package com.tietiao.action.user;

import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.renren.api.client.RenrenApiClient;
import com.renren.api.client.RenrenApiConfig;
import com.renren.api.client.param.impl.AccessToken;
import com.renren.api.client.utils.HttpURLUtils;
import com.tietiao.common.action.BaseAction;
import com.tietiao.common.constants.SysUserConstants;
import com.tietiao.common.constants.TietiaoConstants;
import com.tietiao.common.util.ImageUtils;
import com.tietiao.common.util.TietiaoUtil;
import com.tietiao.dao.model.SysUser;
import com.tietiao.service.sysuser.SysUserService;
import com.tietiao.webservice.kanxin.KxSDK;
import com.tietiao.webservice.qq.beans.Account;
import com.tietiao.webservice.qq.beans.OAuth;
import com.tietiao.webservice.qq.utils.OAuthClient;
/**
 * 调用外部接口处理
 */
@Controller
@Scope("prototype")
public class WebServiceAction extends BaseAction{
	private static final long serialVersionUID = -1061203761388093408L;
	@Resource
	private SysUserService sysUserService;
	private String verify;
	/**
	 * 功能：进行QQ授权跳转
	 */
	public String toOauthQQ() throws Exception {
		OAuth oauth=new OAuth();
		OAuthClient auth=new OAuthClient();
		// 获取request token
		oauth = auth.requestToken(oauth);
		String oauth_token_secret = oauth.getOauth_token_secret();
		if (oauth.getStatus() == 1) {
			System.out.println("Get Request Token failed!");
			return "login";
		} else {
			String oauth_token = oauth.getOauth_token();
			String url = "http://open.t.qq.com/cgi-bin/authorize?oauth_token="+ oauth_token;
			request.getSession().setAttribute("oauth_token", oauth_token);
			request.getSession().setAttribute("oauth_token_secret", oauth_token_secret);
			System.out.println("============"+oauth_token_secret);
			return redirect(url);
		}
	}
	
	/**
	 * 功能：QQ成功授权
	 */
	public String oauthQQSuccess() throws Exception {
		OAuthClient auth=new OAuthClient();
		OAuth oauth=new OAuth();
        //获取access token
        oauth.setOauth_token_secret(request.getSession().getAttribute("oauth_token_secret").toString());
        oauth.setOauth_token(request.getSession().getAttribute("oauth_token").toString());
        String verify = request.getParameter("oauth_verifier");
        String openid = request.getParameter("openid");
        SysUser sysUser = sysUserService.getSysUserByWebService(openid);
        if(sysUser!=null){
        	request.getSession().setAttribute(TietiaoUtil.SESSION_USER, sysUser);
        	return "login_success";
        }else{
        	 oauth.setOauth_verifier(verify);
             oauth = auth.accessToken(oauth);
             System.out.println("Response from server：");
     		if (oauth.getStatus() == 2) {
     			System.out.println("Get Access Token failed!");
     			return "login";
     		} else {		
     			Account account = auth.getAccount(oauth);
     			sysUser = new SysUser();
     			if("1".equals(account.getSex())){
     				sysUser.setGender(SysUserConstants.GENDER_MAN);
     			}else if("0".equals(account.getSex())){
     				sysUser.setGender(SysUserConstants.GENDER_WOMAN);
     			}else{
     				sysUser.setGender(SysUserConstants.GENDER_UNKNOW);
     			}
     			sysUser.setCreateTime(new Date());
     			sysUser.setState(1);
     			sysUser.setIsActive(1);
     			sysUser.setPassword("123456");
     			sysUser.setType(SysUserConstants.TYPE_USER);
     			sysUser.setUserPhoto("/head/head_0.jpg");
     			sysUser.setEmail(account.getEmail());
     			sysUser.setSignature(account.getIntroduction());
     			sysUser.setPetName(account.getName());
     			sysUser.setRelName(account.getNick());
     			sysUser.setColumn4(account.getOpenid());
     			sysUserService.insertSysUser(sysUser);
     			request.getSession().setAttribute(TietiaoUtil.SESSION_USER, sysUser);
     		}
		}
    	return redirect("ucenter_ucenter_stepOne.htm");
	}
	/**
	 * 功能：进行renren授权跳转
	 */
	public String toOauthRenRen() throws Exception {
		 	StringBuffer url = new StringBuffer("https://graph.renren.com/oauth/authorize?");
		 	url.append("client_id=").append("176719");
		 	url.append("&").append("response_type=").append("code");
		 	url.append("&").append("redirect_uri=").append(URLEncoder.encode(TietiaoConstants.RENREN_CALLBACK, "UTF-8"));
		 	url.append("&").append("display=").append("page");
	        //操作的权限,根据具体需求自行选择
		 	url.append("&").append("scope=").append("read_user_status,status_update,read_user_feed,publish_feed,photo_upload");
		 	url.append("&").append("x_renew=").append("true"); //设置每次使用人人连接用户都需要登陆
			return redirect(url.toString());
	}
	
	/**
	 * 功能：进行renren授权跳转
	 */
	public String oauthRenRen() throws Exception {
        String code = request.getParameter("code");
        //到人人网的OAuth 2.0的token endpoint用code换取access token
        String rrOAuthTokenEndpoint = "https://graph.renren.com/oauth/token";
        Map<String, String> parameters = new HashMap<String, String>();
        parameters.put("client_id", RenrenApiConfig.renrenApiKey);
        parameters.put("client_secret", RenrenApiConfig.renrenApiSecret);
        parameters.put("redirect_uri", TietiaoConstants.RENREN_CALLBACK);
        parameters.put("grant_type", "authorization_code");
        parameters.put("code", code);
        parameters.put("scope","read_user_status,read_user_feed,publish_feed,photo_upload");
        String tokenResult = HttpURLUtils.doPost(rrOAuthTokenEndpoint, parameters);
        JSONObject tokenJson = (JSONObject) JSONValue.parse(tokenResult);
        
        //调用SDK获得用户信息
        if (tokenJson != null) {
            String accessToken = (String) tokenJson.get("access_token");
            RenrenApiClient apiClient = RenrenApiClient.getInstance();
            int rrUid = apiClient.getUserService().getLoggedInUser(new AccessToken(accessToken));
            StringBuffer prop = new StringBuffer();
            prop.append("uid").append(",").append("name").append(",").append("sex").append(",").append("birthday").append(",")
            .append("email_hash").append(",").append("headurl").append(",")
            .append("province").append(",").append("city").append(",").append("university_info");
            JSONArray userInfo = apiClient.getUserService().getInfo(String.valueOf(rrUid),prop.toString(), new AccessToken(accessToken));
            if (userInfo != null && userInfo.size() > 0) {
                JSONObject currentUser = (JSONObject) userInfo.get(0);
                SysUser sysUser = sysUserService.getSysUserByWebService(currentUser.get("uid")+"");
                if(sysUser!=null){
                	request.getSession().setAttribute(TietiaoUtil.SESSION_USER, sysUser);
                	return "login_success";
                }else{
         			sysUser = new SysUser();
         			if("1".equals(currentUser.get("sex"))){
         				sysUser.setGender(SysUserConstants.GENDER_MAN);
         			}else if("0".equals(currentUser.get("sex"))){
         				sysUser.setGender(SysUserConstants.GENDER_WOMAN);
         			}else{
         				sysUser.setGender(SysUserConstants.GENDER_UNKNOW);
         			}
         			sysUser.setCreateTime(new Date());
         			sysUser.setState(1);
         			sysUser.setIsActive(1);
         			sysUser.setPassword("123456");
         			sysUser.setType(SysUserConstants.TYPE_USER);
         			sysUser.setUserPhoto("/head/head_0.jpg");
         			sysUser.setEmail(currentUser.get("email_hash")+"");
         			sysUser.setSignature("什么都没有写");
         			sysUser.setRelName(currentUser.get("name")+"");
         			sysUser.setPetName(sysUser.getRelName());
         			sysUser.setColumn4(currentUser.get("uid")+"");
         			sysUser.setCity(currentUser.get("city")==null?"":currentUser.get("city").toString());
         			sysUser.setProvince(currentUser.get("province")==null?"":currentUser.get("province").toString());
         			sysUser.setSchool("");
         			sysUserService.insertSysUser(sysUser);
         			Object url = currentUser.get("headurl");
         			if(url!=null){
         				String picName = "/head/head_"+sysUser.getUserId()+ url.toString().substring(url.toString().lastIndexOf("."));
        				String picPath = TietiaoConstants.PIC_ROOT_PATH + picName;
        				boolean result = ImageUtils.convertFromNet(TietiaoConstants.RESULT_USER_PHOTO_H, TietiaoConstants.RESULT_USER_PHOTO_W,
        							new URL(url.toString()), picPath);
        				if(result){
        					sysUser.setUserPhoto(picName);
        					sysUser.setPetName(sysUser.getPetName()+"_"+sysUser.getUserId());
        					sysUserService.updateSysUser(sysUser);
        				}
         			}else{
         				sysUser.setPetName(sysUser.getPetName()+"_"+sysUser.getUserId());
    					sysUserService.updateSysUser(sysUser);
         			}
         			request.getSession().setAttribute(TietiaoUtil.SESSION_USER, sysUser);
         			return redirect("ucenter_ucenter_stepOne.htm");
         		}
            }
        }
        return "login_success";
	}
	
	/**
	 * 功能：Kaixin授权跳转
	 */
	public String toOauthKaixin() throws Exception {
		String scope = "create_records";
		return redirect(new KxSDK().getAuthorizeURLforCode(scope,"",""));
	}
	
	/**
	 * 功能：Kaixin授权跳转
	 */
	public String oauthKaixin() throws Exception {
		String code = request.getParameter("code");
		if(code!=null){
			KxSDK sdk = new KxSDK();
			com.tietiao.webservice.kanxin.http.AccessToken accessToken = sdk.getOAuthAccessTokenFromCode(code);
			if(accessToken!=null){
				 String fields = "uid,name,gender,hometown,logo120,birthday,intro,school,pinyin";
				 sdk.setOAuthAccessToken(accessToken);
				 com.tietiao.webservice.kanxin.User user = sdk.getMyInfo(fields);
				 SysUser sysUser = sysUserService.getSysUserByWebService(user.getUid()+"");
	                if(sysUser!=null){
	                	request.getSession().setAttribute(TietiaoUtil.SESSION_USER, sysUser);
	                	return "login_success";
	                }else{
	         			sysUser = new SysUser();
	         			if(user.getGender()==1){
	         				sysUser.setGender(SysUserConstants.GENDER_WOMAN);
	         			}else{
	         				sysUser.setGender(SysUserConstants.GENDER_MAN);
	         			}
	         			sysUser.setCreateTime(new Date());
	         			sysUser.setState(1);
	         			sysUser.setIsActive(1);
	         			sysUser.setPassword("123456");
	         			sysUser.setType(SysUserConstants.TYPE_USER);
	         			sysUser.setUserPhoto("/head/head_0.jpg");
	         			sysUser.setEmail("");
	         			sysUser.setSignature(user.getIntro());
	         			sysUser.setPetName(user.getName());
	         			sysUser.setRelName(user.getName());
	         			sysUser.setColumn4(user.getUid()+"");
	         			sysUser.setCity(user.getCity());
	         			sysUser.setProvince(user.getHometown());
	         			sysUser.setSchool("");
	         			
	         			sysUserService.insertSysUser(sysUser);
	         			Object url = user.getLogo120();
	         			if(url!=null){
	         				String picName = "/head/head_"+sysUser.getUserId()+ url.toString().substring(url.toString().lastIndexOf("."));
	        				String picPath = TietiaoConstants.PIC_ROOT_PATH + picName;
	        				boolean result = ImageUtils.convertFromNet(TietiaoConstants.RESULT_USER_PHOTO_H, TietiaoConstants.RESULT_USER_PHOTO_W,
	        							new URL(url.toString()), picPath);
	        				if(result){
	        					sysUser.setUserPhoto(picName);
	        					sysUser.setPetName(sysUser.getPetName()+"_"+sysUser.getUserId());
	        					sysUserService.updateSysUser(sysUser);
	        				}
	         			}else{
	         				sysUser.setPetName(sysUser.getPetName()+"_"+sysUser.getUserId());
	         				sysUserService.updateSysUser(sysUser);
	         			}
	         			request.getSession().setAttribute(TietiaoUtil.SESSION_USER, sysUser);
	         			return redirect("ucenter_ucenter_stepOne.htm");
	         		}
			}else{
				System.out.println("access token request error");
			}	
		}else{
			
		}
		
		return "login_success";
	}
	
	public String getVerify() {
		return verify;
	}
	public void setVerify(String verify) {
		this.verify = verify;
	}

}
